package com.tanhua.locationmanager.util;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Component
public class MyFDfs {

    private final FastFileStorageClient storageClient;
    private final FdfsWebServer fdfsWebServer;

    public MyFDfs(FastFileStorageClient storageClient, FdfsWebServer fdfsWebServer) {
        this.storageClient = storageClient;
        this.fdfsWebServer = fdfsWebServer;
    }

    public String upload(MultipartFile uploadFile) throws IOException {
        InputStream inputStream = uploadFile.getInputStream();
        long fileSize = uploadFile.getSize();
        String filename = uploadFile.getOriginalFilename();
        if (filename == null) throw new IOException("文件名为空");
        String extension = filename.substring(filename.lastIndexOf(".")+1);
        StorePath storePath = storageClient.uploadFile(inputStream, fileSize, extension, null);
        return fdfsWebServer.getWebServerUrl()+storePath.getFullPath();
    }
}
